/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.support.scripting.impl.js;

import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.lang.Files;
import cn.easyplatform.support.scripting.RhinoScriptable;
import cn.easyplatform.support.scripting.ScriptEngine;
import cn.easyplatform.support.scripting.ScriptEntry;
import cn.easyplatform.support.scripting.ScriptUtils;
import cn.easyplatform.support.scripting.cmd.MainCmd;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.RhinoException;
import org.mozilla.javascript.Wrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map.Entry;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class RhinoScriptEngine implements ScriptEngine {

    private final static Logger log = LoggerFactory.getLogger(RhinoScriptEngine.class);

    private CommandContext cc;

    private String expression;

    private Object ns;

    static String functions;

    //private ScriptCmdExecutor cmd;

    static {
        ContextFactory.initGlobal(new ContextFactory() {
            protected Context makeContext() {
                Context cx = super.makeContext();
                cx.setClassShutter(RhinoClassShutter.getInstance());
                cx.setWrapFactory(RhinoWrapFactory.getInstance());
                return cx;
            }

            public boolean hasFeature(Context cx, int feature) {
                // 不需要支持 E4X (ECMAScript for XML)!
                if (feature == Context.FEATURE_E4X) {
                    return false;
                } else {
                    return super.hasFeature(cx, feature);
                }
            }
        });
        //InputStream is = RhinoScriptEngine.class.getResourceAsStream("cmd.so");
        functions = Files.read("META-INF/cmd.so");
    }

    private RhinoScriptable scope;

    @Override
    public ScriptEngine init(ScriptEntry entry) {
        cc = entry.getCommandContext();
        expression = entry.getScript();
        ns = entry.getNameSpace();
        Context cx = Context.enter();
        try {
            cx.setOptimizationLevel(-1);
            if (ns == null) {
                if (cc.getUser().isDebugEnabled())
                    cc.send("script:" + expression);
                else if (log.isDebugEnabled())
                    log.debug("script {}", expression);
                scope = new RhinoScriptable();
                scope.initStandardObjects(cx, false);
                //ScriptCmdExecutor cmd =
                ScriptUtils.createVariables(scope, cc,
                        cc.getWorkflowContext(), entry.getContexts());
                // 准备内嵌的函数
                cx.evaluateString(scope, functions, "", 1, null);
//				if (cc.getUser().isDebugLogicEnabled()) {
//					cc.send(I18N.getLable("script.engine.system.var", cmd
//							.getTarget().getSystemVars()));
//					cc.send(I18N.getLable("script.engine.user.var", cmd
//							.getTarget().getParameter("808")));
//					cc.send(cmd.getTarget().getUserVars());
//					cc.send(I18N.getLable("script.engine.field.var", cmd
//							.getTarget().getParameter("808")));
//					cc.send(cmd.getTarget().getRecordFieldValues());
//					cc.send("script:" + expression);
//				}
            } else {
                scope = (RhinoScriptable) ns;
                //ScriptCmdExecutor cmd = (ScriptCmdExecutor) scope.getVariable("$");
                for (Entry<String, Object> e : scope.getScope().entrySet()) {
                    if (e.getValue() instanceof MainCmd)
                        ((MainCmd) e.getValue()).setEngine(cc);
                }
            }
        } catch (RhinoException ex) {
            throw ScriptUtils.handleScriptException(cc, ex);
        } finally {
            Context.exit();
        }
        return this;
    }

    @Override
    public Object eval(int line) {
        Context cx = Context.enter();
        try {
            cx.setOptimizationLevel(-1);
            Object result = cx.evaluateString(scope, this.expression, "", line, null);
//			if (cc.getUser().isDebugLogicEnabled()) {
//				cc.send(I18N.getLable("script.engine.system.var", cmd
//						.getTarget().getSystemVars()));
//				cc.send(I18N.getLable("script.engine.user.var", cmd.getTarget()
//						.getParameter("808")));
//				cc.send(cmd.getTarget().getUserVars());
//				cc.send(I18N.getLable("script.engine.field.var", cmd
//						.getTarget().getParameter("808")));
//				cc.send(cmd.getTarget().getRecordFieldValues());
//			}
            if (result == null)
                return null;
            else if (result instanceof Wrapper)
                return ((Wrapper) result).unwrap();
            else
                return result;
        } catch (RhinoException ex) {
            throw ScriptUtils.handleScriptException(cc, ex);
        } finally {
            Context.exit();
        }
    }

    @Override
    public Object getNameSpace() {
        return scope;
    }

    @Override
    public void destroy() {
        if (scope != null) {
            scope.clear();
            scope = null;
        }
    }

}
